<?php

/**
 *    会员中心页面
 *
 *    @author liangcajian QQ632324010
 *    @usage    none
 */
class MemberApp extends MemberbaseApp
{
    var $_feed_enabled = false;
    function __construct()
    {
        $this->MemberApp();
    }
    function MemberApp()
    {
        parent::__construct();
    }
    function index()
    {
		$user = $this->visitor->get();
		empty($user['portrait']) && $user['portrait'] = Conf::get('default_user_portrait');
        $this->assign('user', $user);
        if (!$user['store_id'])//这里是会员
		{
			//我的运单
			$kd_order_mod =& m('kd_order');
			$kd_yubao_mod =& m('kd_yubao');
			$show_number = array(
			  'daifukuan'=>$kd_order_mod->getOne("SELECT COUNT(*) FROM {$kd_order_mod->table} WHERE user_id='{$user['user_id']}' AND status = '3'"), //待付款
			  //'yifahuo'=>$kd_order_mod->getOne("SELECT COUNT(*) FROM {$kd_order_mod->table} WHERE user_id='{$user['user_id']}' AND status = '7'"),//已发货
			  //'weiruku'=>$kd_order_mod->getOne("SELECT COUNT(*) FROM {$kd_order_mod->table} WHERE user_id='{$user['user_id']}' AND status = '0'"),//未入库
			  'yirukubaoguo'=>$kd_yubao_mod->getOne("SELECT COUNT(*) FROM {$kd_yubao_mod->table} WHERE user_id='{$user['user_id']}' AND status = '1'"), //已入库包裹
			  //'yifachubaoguo'=>$kd_yubao_mod->getOne("SELECT COUNT(*) FROM {$kd_yubao_mod->table} WHERE user_id='{$user['user_id']}' AND status = '2'"),//已发出包裹
			  //'wentijian'=>$kd_yubao_mod->getOne("SELECT COUNT(*) FROM {$kd_yubao_mod->table} WHERE user_id='{$user['user_id']}' AND status = '4'"),//问题件			  
			);	
			$this->assign('show_number', $show_number);
		}		

        /* 待审核提醒 */
        if ( $user['state'] != '' && $user['state'] == STORE_APPLYING )
        {
            $this->assign('applying', 1);
        }
		//会员资金管理=======================================
		$my_money_mod =& m('my_money');
		$money_money=$my_money_mod->getRow("select money,money_dj,rz_is_ok from {$my_money_mod->table} where user_id='{$this->visitor->get('user_id')}'");
		if(!$money_money){
			/*by:liangcaijian 帐户资金自动注册开通 开始******************************/
			$my_money_mod->add(array( 'user_id' => $this->visitor->get('user_id'), 'user_name' => $this->visitor->get('user_name'), 'add_time' => gmtime() ));	
		}
		$this->assign('money_money', $money_money);
		//会员资金管理=======================================
		
        /* 当前位置 */
        $this->_curlocal(LANG::get('member_center'),url('app=member'),
                         LANG::get('overview'));

        /* 当前用户中心菜单 */
        $this->_curitem('overview');
        $this->_config_seo('title', Lang::get('member_center')  . ' - ' . Conf::get('site_name') );
        $this->display('member.index.html');
    }
	function certificate()
	{
        //rz_is_ok 0、未申请 1、申请中等待审核 2、拒绝通过 3、审核通过
		$my_money_mod =& m('my_money');
        $my_money = $my_money_mod->get(array('conditions' => "user_id=".$this->visitor->get('user_id')));	
		if($_POST)
		{
			if ($my_money['rz_is_ok'] == 3)
			{
				  $this->show_warning('已经审核通过了，无法再进行修改或申请，如需要修改，请联系客服后台修改!');
				  return;				
			}
			  if (empty($_POST['real_name']))
			  {
				  $this->show_warning('请填写申请人的真实姓名');
				  return;
			  }
			  if (empty($_POST['id_card']))
			  {
				  $this->show_warning('请填写申请人身份证号码');
				  return;
			  }
			  if (empty($_POST['mobile']))
			  {
				  $this->show_warning('联系人手机必填项:申请人的手机号码格式为11位的数字');
				  return;
			  }	
			  if (empty($_POST['bank_subbranch']))
			  {
				  $this->show_warning('请填写支行名称');
				  return;
			  }		
			  if (empty($_POST['bank_account']))
			  {
				  $this->show_warning('请填写申请人的银行帐号');
				  return;
			  }	
			  $data = array(
				  'rz_is_ok'        => 1,
				  'real_name'       => htmldecode($_POST['real_name']),
				  'id_card'         => htmldecode($_POST['id_card']),
				  'card_validity'   => isset($_POST['is_extended']) ? '长期有效' : htmldecode($_POST['card_validity']),
				  'address'         => htmldecode($_POST['address']),
				  'mobile'          => htmldecode($_POST['mobile']),
				  'real_name'       => htmldecode($_POST['real_name']),
				  'bank_name'       => htmldecode($_POST['bank_name']),						
				  'bank_province'   => htmldecode($_POST['region_name']),
				  'bank_subbranch'  => htmldecode($_POST['bank_subbranch']),
				  'bank_account'    => htmldecode($_POST['bank_account']),
				  'rz_sc_time'      => gmtime(),
				  'rz_refused'      => '',
			  );			  
			  //传身份证图片
			  $image = $this->_upload_image($this->visitor->get('user_id'));
			  if ($this->has_error())
			  {
				  $this->show_warning($this->get_error());
				  return;
			  }	
			  $my_money_mod->edit("user_id = ".$this->visitor->get('user_id'), array_merge($data, $image));
			  if ($my_money_mod->has_error())
			  {
				  $this->show_warning($my_money_mod->get_error());
				  return;
			  }			  
			  $this->show_message('application_ok');	  
			  				  			  		  			  			  
		}else{
			$this->assign('my_money', $my_money);
			$region_mod =& m('region');
			$this->assign('regions', $region_mod->get_options(1));
			$this->import_resource('jquery.plugins/jquery.validate.js,mlselection.js');
			/* 当前用户中心菜单 */
			$this->_curitem('my_certificate');
			$this->_curmenu('my_certificate');
			$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_certificate'));		
			$this->display('member.certificate.html');
		}
	}

    /**
     *    修改基本信息
     *
     *    @author    Hyber
     *    @usage    none
     */
    function profile(){

        $user_id = $this->visitor->get('user_id');
        if (!IS_POST)
        {
            /* 当前位置 */
            $this->_curlocal(LANG::get('member_center'),  'index.php?app=member',
                             LANG::get('basic_information'));

            /* 当前用户中心菜单 */
            $this->_curitem('my_profile');

            /* 当前所处子菜单 */
            $this->_curmenu('basic_information');

//            $ms =& ms();    //连接用户系统
//            $edit_avatar = $ms->user->set_avatar($this->visitor->get('user_id')); //获取头像设置方式

            $model_user =& m('member');
            $profile    = $model_user->get_info(intval($user_id));
            //$profile['portrait'] = portrait($profile['user_id'], $profile['portrait'], 'middle');
			if (!$user['portrait']){ $user['portrait'] = Conf::get('default_user_portrait');   }
            $this->assign('profile',$profile);
			$this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,datePicker/WdatePicker.js'));			
            $this->assign('edit_avatar', $edit_avatar);
			$this->assign('default_user_portrait', Conf::get('default_user_portrait'));
            $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_profile'));
            $this->display('member.profile.html');
        }
        else
        {
            $data = array(
                'real_name' => htmldecode($_POST['real_name']),
                'gender'    => htmldecode($_POST['gender']),
                'birthday'  => htmldecode($_POST['birthday']),
                'im_qq'     => htmldecode($_POST['im_qq']),
                'phone_mob' => htmldecode($_POST['phone_mob']),
				'phone_tel' => htmldecode($_POST['phone_tel']),
				'idpic' => htmldecode($_POST['idpic']),
            );

            if (!empty($_POST['c_input']))
            {
				$c_input = str_replace('/data/','data/',$_POST['c_input']);
				if(file_exists($c_input)){
					$base_name = explode(".",basename($c_input));;
					//复制图片过去
					$pic_file = "data/files/mall/portrait/".ceil($user_id / 500);
					$portrait = $pic_file .'/' . $user_id . '.' . $base_name[1];
					if (!is_dir($pic_file))
					{
						ecm_mkdir(ROOT_PATH . '/' . $pic_file);
					}   					
					copy($c_input,$portrait);
					unlink($c_input);
				}
				
//                $portrait = $this->_upload_portrait($user_id);
//                if ($portrait === false)
//                {
//                    return;
//                }
                $data['portrait'] = $portrait;
            }

            $model_user =& m('member');
            $model_user->edit($user_id , $data);
            if ($model_user->has_error())
            {
                $this->show_warning($model_user->get_error());
                return;
            }
			$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '修改个人资料', 0);//添加操作日志	

            $this->show_message('edit_profile_successed');
        }
    }
    /**
     *    修改密码
     *
     *    @author    Hyber
     *    @usage    none
     */
    function password(){
        $user_id = $this->visitor->get('user_id');
        if (!IS_POST)
        {
            /* 当前位置 */
            $this->_curlocal(LANG::get('member_center'),  'index.php?app=member',
                             LANG::get('edit_password'));

            /* 当前用户中心菜单 */
            $this->_curitem('my_password');

            /* 当前所处子菜单 */
            $this->_curmenu('edit_password');
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js',
            ));
            $this->_config_seo('title', Lang::get('user_center') . ' - ' . Lang::get('edit_password'));
            $this->display('member.password.html');
        }
        else
        {
            /* 两次密码输入必须相同 */
            $orig_password      = $_POST['orig_password'];
            $new_password       = $_POST['new_password'];
            $confirm_password   = $_POST['confirm_password'];
            if ($new_password != $confirm_password)
            {
                $this->show_warning('twice_pass_not_match');
                return;
            }
            if (!$new_password)
            {
                $this->show_warning('no_new_pass');
                return;
            }
            $passlen = strlen($new_password);
            if ($passlen < 6 || $passlen > 20)
            {
                $this->show_warning('password_length_error');
                return;
            }

            /* 修改密码 */
            $ms =& ms();    //连接用户系统
            $result = $ms->user->edit($this->visitor->get('user_id'), $orig_password, array(
                'password'  => $new_password
            ));
            if (!$result)
            {
                /* 修改不成功，显示原因 */
                $this->show_warning($ms->user->get_error());
                return;
            }
			$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '修改密码', 0);//添加操作日志	

            $this->show_message('edit_password_successed');
        }
    }
    /**
     *    修改电子邮箱
     *
     *    @author    Hyber
     *    @usage    none
     */
    function email(){
        $user_id = $this->visitor->get('user_id');
		$user_mod =& m('member');
		$member_email=$user_mod->getRow("select user_id,user_name,email from ".DB_PREFIX."member where user_id='$user_id'");
        if (!IS_POST)
        {
            /* 当前位置 */
            $this->_curlocal(LANG::get('member_center'),  'index.php?app=member',
                             LANG::get('edit_email'));

            /* 当前用户中心菜单 */
            $this->_curitem('my_email');

            /* 当前所处子菜单 */
            $this->_curmenu('edit_email');
			
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js',
            ));
			$this->assign('member_email', $member_email['email']);
            $this->_config_seo('title', Lang::get('user_center') . ' - ' . Lang::get('edit_email'));
            $this->display('member.email.html');
        }
        else
        {
		    $email = htmldecode($_POST['email']);
            if (!$email)
            {
                $this->show_warning('email_required');
                return;
            }
            if (!is_email($email))
            {
                $this->show_warning('email_error');
                return;
            }
			$this->assign('send_mail_ok', 'ok');
            /* 当前位置 */
            $this->_curlocal(LANG::get('member_center'),  'index.php?app=member',
                             LANG::get('edit_email'));
            $this->_curitem('my_email');
            $this->_curmenu('edit_email');
			$this->assign('new_email', $email);
            $this->_config_seo('title', Lang::get('user_center') . ' - ' . Lang::get('edit_email'));
            $word = $this->_rand();
            $md5word = md5($word);
            $user_mod->edit($user_id, array('activation' => "{$md5word}"));
            $mail = get_mail('touser_mod_email', array('user' => $member_email,'email' => $email, 'word' => $word));
			//print_r($mail);
			$this->_mailto($email, addslashes($mail['subject']), addslashes($mail['message']));			
            $this->display('member.email.html');			
        }
    }

    /**
     * Feed设置
     *
     * @author Garbin
     * @param
     * @return void
     **/
    function feed_settings()
    {
        if (!$this->_feed_enabled)
        {
            $this->show_warning('feed_disabled');
            return;
        }
        if (!IS_POST)
        {
            /* 当前位置 */
            $this->_curlocal(LANG::get('member_center'),  'index.php?app=member',
                             LANG::get('feed_settings'));

            /* 当前用户中心菜单 */
            $this->_curitem('my_profile');

            /* 当前所处子菜单 */
            $this->_curmenu('feed_settings');
            $this->_config_seo('title', Lang::get('user_center') . ' - ' . Lang::get('feed_settings'));

            $user_feed_config = $this->visitor->get('feed_config');
            $default_feed_config = Conf::get('default_feed_config');
            $feed_config = !$user_feed_config ? $default_feed_config : unserialize($user_feed_config);

            $buyer_feed_items = array(
                'store_created' => Lang::get('feed_store_created.name'),
                'order_created' => Lang::get('feed_order_created.name'),
                'goods_collected' => Lang::get('feed_goods_collected.name'),
                'store_collected' => Lang::get('feed_store_collected.name'),
                'goods_evaluated' => Lang::get('feed_goods_evaluated.name'),
                'groupbuy_joined' => Lang::get('feed_groupbuy_joined.name')
            );
            $seller_feed_items = array(
                'goods_created' => Lang::get('feed_goods_created.name'),
                'groupbuy_created' => Lang::get('feed_groupbuy_created.name'),
            );
            $feed_items = $buyer_feed_items;
            if ($this->visitor->get('manage_store'))
            {
                $feed_items = array_merge($feed_items, $seller_feed_items);
            }
            $this->assign('feed_items', $feed_items);
            $this->assign('feed_config', $feed_config);
            $this->display('member.feed_settings.html');
        }
        else
        {
            $feed_settings = serialize($_POST['feed_config']);
            $m_member = &m('member');
            $m_member->edit($this->visitor->get('user_id'), array(
                'feed_config' => $feed_settings,
            ));
            $this->show_message('feed_settings_successfully');
        }
    }

     /**
     *    三级菜单
     *
     *    @author    Hyber
     *    @return    void
     */
    function _get_member_submenu()
    {
        $submenus =  array(
            array(
                'name'  => 'basic_information',
                'url'   => 'index.php?app=member&amp;act=profile',
            ),
            array(
                'name'  => 'edit_password',
                'url'   => 'index.php?app=member&amp;act=password',
            ),
            array(
                'name'  => 'edit_email',
                'url'   => 'index.php?app=member&amp;act=email',
            ),
        );
        if ($this->_feed_enabled)
        {
            $submenus[] = array(
                'name'  => 'feed_settings',
                'url'   => 'index.php?app=member&amp;act=feed_settings',
            );
        }

        return $submenus;
    }

    /**
    /* 上传身份证图片 */
    function _upload_image($user_id)
    {
        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->allowed_size(SIZE_STORE_CERT); // 400KB

        $data = array();

		$file = $_FILES['card_pic'];
		if ($file['error'] == UPLOAD_ERR_OK)
		{
			if (empty($file))
			{
				continue;
			}
			$uploader->addFile($file);
			if (!$uploader->file_info())
			{
				$this->_error($uploader->get_error());
				return false;
			}

			$uploader->root_dir(ROOT_PATH);
			$dirname   = 'data/files/mall/application';
			$filename  = 'user_' . $user_id . '_card_pic';
			$data['card_pic'] = $uploader->save($dirname, $filename);
		}
        return $data;
    }	
    /**
     * 构造15位的随机字符串
     *
     * @return string | 生成的字符串
     */
    function _rand()
    {
        $word = $this->generate_code();
        return $word;
    }

    function generate_code($len = 15)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0, $count = strlen($chars); $i < $count; $i++)
        {
            $arr[$i] = $chars[$i];
        }

        mt_srand((double) microtime() * 1000000);
        shuffle($arr);
        $code = substr(implode('', $arr), 5, $len);
        return $code;
    }	
	

    /**
     *    注册一个新用户
     *
     *    @author liangcajian QQ632324010
     *    @return    void
     */
    function register()
    {
        if ($this->visitor->has_login)
        {
            $this->show_warning('has_login');
            return;
        } 
        if (!IS_POST)
        {
            if (!empty($_GET['ret_url'])){
                $ret_url = htmldecode($_GET['ret_url']);
            }else{
                if (isset($_SERVER['HTTP_REFERER'])){
                    $ret_url = $_SERVER['HTTP_REFERER'];
                }else{
                    $ret_url = SITE_URL . '/index.php';
                }
            }
			
            $this->assign('ret_url', rawurlencode($ret_url));
            $this->_curlocal(LANG::get('user_register'));
            $this->_config_seo('title', Lang::get('user_register') . ' - ' . Conf::get('site_title'));

            if (Conf::get('captcha_status.register')){
                $this->assign('captcha', 1);
            }

            /* 导入jQuery的表单验证插件 */
            $this->import_resource('jquery.plugins/jquery.validate.js');
            $this->display('member.register.html');
        }
        else
        {

            if (!$_POST['agree'])
            {
                $this->show_warning('agree_first');
                return;
            }
            if (Conf::get('captcha_status.register') && base64_decode($_SESSION['captcha']) != strtolower($_POST['captcha']))
            {
                $this->show_warning('captcha_failed');
                return;
            }
            if ($_POST['password'] != $_POST['password_confirm'])
            {
                /* 两次输入的密码不一致 */
                $this->show_warning('inconsistent_password');
                return;
            }

            /* 注册并登陆 */
            $user_name = htmldecode($_POST['user_name']);
            $password  = htmldecode($_POST['password']);
            $email     = htmldecode($_POST['email']);
            $passlen   = strlen($password);
            $user_name_len = strlen($user_name);
            if ($user_name_len < 2 || $user_name_len > 25)
            {
                $this->show_warning('user_name_length_error');
                return;
            }
            if ($passlen < 6 || $passlen > 20)
            {
                $this->show_warning('password_length_error');
                return;
            }
            if (!is_email($email))
            {
                $this->show_warning('email_error');
                return;
            }

            $ms =& ms(); //连接用户中心
            $user_id = $ms->user->register($user_name, $password, $email);
            if (!$user_id)
            {
                $this->show_warning($ms->user->get_error());
                return;
            }			

            $this->_hook('after_register', array('user_id' => $user_id));
            //登录
            $this->_do_login($user_id);
            /* 同步登陆外部系统 */
            $synlogin = $ms->user->synlogin($user_id);

            //同步修改电话和所在区域
			$data = array(
                'phone_mob' => htmldecode($_POST['phone_mob']),
                'idpic'     => htmldecode($_POST['idpic']),
                'im_qq'     => htmldecode($_POST['im_qq']),
            );
            $model_user =& m('member');
            $model_user->edit($user_id , $data);
			
            $this->show_message('恭喜您注册成功！',
                '进入会员中心', 'index.php?app=member',
                '修改会员资料', 'index.php?app=member&act=profile'
            );			
			 /* #TODO 可能还会发送欢迎邮件 //注册成功后提示用户用户去哪里*/
			//header('location:index.php?app=member&act=register_ok&ret_url='.$_POST['ret_url']);
        }
    }
	//注册成功，提示用户选择开店店铺
	function register_ok()
	{
		if ( strpos($_GET['ret_url'], "order") || strpos($_GET['ret_url'], "cart") )
		{
			header('location:' . $_GET['ret_url']);
		}
		$this->display('member.register_ok.html');
	}
	
	/***********************会员登录**********************************/
	
    function login()
    {
        if ($this->visitor->has_login)
        {
			$this->show_warning('has_login', '进入会员中心', 'index.php?app=member');

            return;
        }
        if (!IS_POST)
        {
            if (!empty($_GET['ret_url']))
            {
                $ret_url = htmldecode($_GET['ret_url']);
            }
            else
            {
                if (isset($_SERVER['HTTP_REFERER']))
                {
                    $ret_url = $_SERVER['HTTP_REFERER'];
                }
                else
                {
                    $ret_url = SITE_URL . '/';
                }
            }
            /* 防止登陆成功后跳转到登陆、退出的页面 */
            $ret_url = strtolower($ret_url);            
            if (str_replace(array('act=login', 'act=logout',), '', $ret_url) != $ret_url)
            {
                $ret_url = SITE_URL . '/';
            }

            if (Conf::get('captcha_status.login'))
            {
                $this->assign('captcha', 1);
            }
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
            $this->assign('ret_url', rawurlencode($ret_url));
            $this->_curlocal(LANG::get('user_login'));
            $this->_config_seo('title', Lang::get('user_login') . ' - ' . Conf::get('site_title'));
            $this->display('login.html');
        }
        else
        {
            if (Conf::get('captcha_status.login') && base64_decode($_SESSION['captcha']) != strtolower($_POST['captcha']))
            {
                $this->show_warning('captcha_failed');
                return;
            }

            $user_name = htmldecode($_POST['user_name']);
            $password  = htmldecode($_POST['password']);

            $ms =& ms();
            $user_id = $ms->user->auth($user_name, $password);
          
			if (!$user_id)
            {
                /* 未通过验证，提示错误信息 */
                $this->show_warning($ms->user->get_error());
                return;
            }
            else
            {
                /* 通过验证，执行登陆操作 */
                $this->_do_login($user_id);
                /* 同步登陆外部系统 */
                $synlogin = $ms->user->synlogin($user_id);
            }

            $this->show_message(Lang::get('login_successed') . $synlogin,
                'back_before_login', rawurldecode($_POST['ret_url']),
                'enter_member_center', 'index.php?app=member'
            );
        }
    }

    function logout()
    {
        $this->visitor->logout();

		/* 同步退出外部系统 */
		$ms =& ms();
		echo $synlogout = $ms->user->synlogout();

        /*执行成功后跳转到网站首页*/
		header("Location: ".SITE_URL);
        return;
    }

    /**
     *    检查用户是否存在
     *
     *    @author liangcajian QQ632324010
     *    @return    void
     */
    function check_user()
    {
        $user_name = empty($_GET['user_name']) ? null : htmldecode($_GET['user_name']);
        if (!$user_name)
        {
            echo ecm_json_encode(false);

            return;
        }
        $ms =& ms();

        echo ecm_json_encode($ms->user->check_username($user_name));
    }
	/*  首页登录框登录 */
	function login_index()
	{
		$user_name = htmldecode($_POST['username']);
		$password  = htmldecode($_POST['password']);
		$ms =& ms();
		$user_id = $ms->user->auth($user_name, $password);
		if ($user_id)
		{
			/* 通过验证，执行登陆操作 */
			$this->_do_login($user_id);
			/* 同步登陆外部系统 */
			$synlogin = $ms->user->synlogin($user_id);	
			$qsjs="<script language=\"javascript\" type=\"text/javascript\">window.location.href=\"index.php?app=member\";</script>";
			exit($qsjs);
					
		}else{
			/* 未通过验证，提示错误信息 */
			//$this->show_warning($ms->user->get_error());
			exit("err");
			echo ecm_json_encode($ms->user->get_error()); return;
		}
	}
	
}
?>